﻿using System.IO;
using System.Net;
using System.Web.Mvc;

using SCB.Common;
using SCB.Presentation.Models;
using SCB.Presentation.Helpers;

namespace SCB.Presentation.Controllers
{
    public class ProductController : Controller
    {
        public ActionResult Index()
        {
            return View("Products");
        }

        public ActionResult ProductDetail(int id, string keyword = "")
        {
            DTOProduct product = ProductService.GetProduct(id);
            string content = GetWebContent(product.Link);

            ViewData["Link"] = product.Link;

            // using for display product detail in database
            product.IsAlive = string.IsNullOrEmpty(content) ? false : true;
            if (!product.IsAlive)
                product.LocationDetail = ProviderService.GetProviderLocation(product.ProviderId, "");

            // update search history
            if (!string.IsNullOrEmpty(keyword))
                SearchHistoryService.UpdateSearchHistory(new DTOSearchHistory() { Text = product.Title, Link = Utilities.GetProductDetailView(id) });
            return View("ProductDetail", product);
        }

        public ActionResult ProductCompare(int id)
        {
            var productModels = new UIProductModels();

            productModels.Product = ProductService.GetProduct(id);
            productModels.Product.LocationDetail = ProviderService.GetProviderLocation(productModels.Product.ProviderId, "");
            productModels.Products = ProductService.GetProductsByProductTitle(id, productModels.Product.Title);
            productModels.ProductsByCategory = ProductService.GetProductsByCategoryId(productModels.Product.CategoryId);

            return View("ProductCompare", productModels);
        }

        public ActionResult Products(string keyword)
        {
            var productModels = new UIProductModels();

            if (!string.IsNullOrEmpty(keyword))
            {
                productModels.Products = ProductService.GetProductsByTitle(keyword);
                SearchHistoryService.UpdateSearchHistory(new DTOSearchHistory() { Text = keyword, Link = Utilities.GetProductsView(keyword) });
            }

            return View("Products", productModels);
        }

        private string GetWebContent(string link)
        {
            string content = string.Empty;

            try
            {
                HttpWebRequest httpRequest = WebRequest.Create(link) as HttpWebRequest;
                HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;

                using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    content = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch { }

            return content;
        }
    }
}